package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 自定义定时任务
 */
@Component
@Slf4j
public class OrderTask {
	
	@Autowired
	private OrderMapper orderMapper;
	
	/**
	 * 解决超时订单
	 */
	@Scheduled(cron = "0 * * * * ?")
	public void overtimeOrders() {
		List<Orders> orders = orderMapper.overtimeOrders(Orders.PENDING_PAYMENT, LocalDateTime.now().plusMinutes(-1));
		if (orders != null && !orders.isEmpty()) {
			for (Orders order : orders) {
				order.setStatus(Orders.CANCELLED);
				order.setCancelReason("订单超时,自动取消");
				order.setCancelTime(LocalDateTime.now());
				orderMapper.updateOrder(order);
			}
		}
	}
	
	/**
	 * 解决派送中订单
	 */
	@Scheduled(cron = "0 0 1 * * ?")
	public void nowDelivery() {
		List<Orders> orders = orderMapper.overtimeOrders(Orders.DELIVERY_IN_PROGRESS, LocalDateTime.now().plusHours(-1));
		if (orders != null && !orders.isEmpty()) {
			for (Orders order : orders) {
				order.setStatus(Orders.COMPLETED);
				orderMapper.updateOrder(order);
			}
		}
	}
}
